<?php


namespace app\service\utils;


use app\common\exception\ApiException;
use app\model\config\FileModel;
use app\Request;
use think\facade\Filesystem;
use think\File;

class UploadService
{
    /**
     * 文件上传
     * @param $uid
     * @param File $file
     * @return array
     * @throws \Exception
     */
    public static function upload($uid, File $file, $type = 0)
    {
        try {
            if (!$uid) {
                throw new ApiException('请先登录');
            }
            if (!$file) {
                throw new ApiException('请上传文件');
            }
            $fileExt = $file->extension();
            $fileOriginName = $file->getOriginalName();
            $fileMd5 = $file->md5();
            $fileSize = $file->getSize();
            $fileMime = $file->getMime();

            $fileCate = self::getFileType($fileExt, true);
            $prefix = $fileCate . '/' . $uid . '/' .$type . '/' .date('Y-m-d') . "/";

            $name = str_replace('.' . $fileExt, '', $fileOriginName);

            $fileInfo = FileModel::where(['md5' => $fileMd5])->find();
            if ($fileInfo) {
                $ret = [
                    "src" => $fileInfo['src'],
                    "name" => $fileInfo['name'],
                    "size" => $fileInfo['size'],
                    "md5" => $fileInfo['md5'],
                    "mime" => $fileInfo['mime'],
                    "ext" => $fileInfo['ext'],
                    'user_id' => $fileInfo['user_id'],
                    'id' => $fileInfo['id'],
                ];
                return $ret;
            }
            $newName = uniqid() . '.' . $fileExt;
            $object = $prefix . $newName;
            $disk = env('filesystem.driver');
            if ($disk == 'public') {
                $object = 'storage/' . $object;
            }
            Filesystem::disk($disk)->putFileAs($prefix, $file, $newName);

            // 把左边的/去掉再加上，避免有些有/有些没有
            $object = '/' . ltrim($object, '/');
            $ret = [
                "src" => $object,
                "name" => $name,
                "size" => $fileSize,
                "md5" => $fileMd5,
                "mime" => $fileMime,
                "ext" => $fileExt,
                'user_id' => $uid,
                'type' => $type,
            ];
            $file = new FileModel;
            $file->save($ret);
            $ret['id'] = $file->id;
            return $ret;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    static function getFileType($ext, $intval = false)
    {
        $ext = strtolower($ext);
        $image = ['jpg', 'jpeg', 'png', 'bmp', 'gif'];
        $radio = ['mp3', 'wav', 'wmv', 'amr'];
        $video = ['mp4', '3gp', 'avi', 'm2v', 'mkv', 'mov'];
        $doc = ['ppt', 'pptx', 'doc', 'docx', 'xls', 'xlsx', 'pdf', 'txt', 'md'];
        $msgType = 'file';
        $msgVal = 3;
        if (in_array($ext, $image)) {
            $msgType = 'image';
            $msgVal = 2;
        } elseif (in_array($ext, $radio)) {
            $msgType = 'voice';
            $msgVal = 4;
        } elseif (in_array($ext, $video)) {
            $msgType = 'video';
            $msgVal = 5;
        }
        return $intval ? $msgType : $msgVal;
    }
}